<template>
  <div class="table">
    <el-table :data="$attrs['tableData']" stripe>
      <el-table-column type="expand">
        <template #default="scope">
          <el-tag
            v-for="(item, i) in scope.row.attr_vals"
            :key="i"
            closable
            @close="closeTag(i, scope.row)"
            >{{ item }}</el-tag
          >
          <el-input
            class="input-new-tag"
            v-if="scope.row.inputVisible"
            v-model="scope.row.inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm(scope.row)"
            @blur="handleInputConfirm(scope.row)"
          >
          </el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput(scope.row)"
            >+ New Tag</el-button
          >
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column
        :label="tableLabels[0]"
        prop="attr_name"
      ></el-table-column>
      <el-table-column :label="tableLabels[1]">
        <template #default="scope">
          <el-button
            icon="el-icon-edit"
            type="primary"
            @click="editClick(scope.row)"
            size="mini"
            >编辑</el-button
          >
          <el-button icon="el-icon-delete" type="danger" size="mini"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "Table",
  inheritAttrs: false,
  data() {
    return {
      tableLabels: ["参数名称", "操作"]
    };
  },
  methods: {
    editClick(param) {
      this.$emit("editClick", param);
    },
    //确认添加标签
    handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      this.saveAttrs(row);
      row.inputVisible = false;
    },
    //删除标签
    closeTag(i, row) {
      //删除选择的标签
      row.attr_vals.splice(i, 1);
      this.saveAttrs(row);
    },
    //编辑标签
    showInput(row) {
      row.inputVisible = true;

      //nextTick页面重新渲染的时候才会执行该函数
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    saveAttrs(row) {
      this.$http
        .put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        })
        .then(res => {
          if (res.data.meta.status == 200) {
            this.$message.success("添加成功");
          } else {
            return;
          }
        })
        .catch(err => err);
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tag {
  margin-right: 10px;
}
.el-input {
  width: 50px;
}
</style>
